package com.anbinh.doctor.fragment.account;

import java.util.Calendar;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.provider.ContactsContract;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;

import com.anbinh.doctor.R;
import com.anbinh.doctor.model.CityResponse;
import com.anbinh.doctor.model.DataResponse;
import com.anbinh.doctor.model.DistrictResponse;
import com.anbinh.doctor.model.ProfileResponse.Data.Profile;
import com.anbinh.doctor.model.ResponseAssistants.Data.Assistants;
import com.anbinh.doctor.model.UserLogin;
import com.anbinh.doctor.request.controller.ServerController;
import com.anbinh.doctor.service.request.OnRequest;
import com.anbinh.doctor.utils.IRcallBak;
import com.anbinh.doctor.utils.Utils;
import com.zcw.togglebutton.ToggleButton;
import com.zcw.togglebutton.ToggleButton.OnToggleChanged;

public class FragmentAddAssistant extends Fragment {
	private static FragmentAddAssistant fragment = null;
	private static boolean isUpdate;
	private View mView;
	private View mLoadding;
	private UserLogin userLogin;
	private TextView lblTinhthanh;
	private TextView lblQuanhuyen;
	private TextView lblGender;
	private TextView lblNgaysinh;
	private EditText edPhone;

	private View spTinhThanh;
	private View spQuanHuyen;
	private int mCity_id = 1;
	private int mDistrict_id = 1;
	private String mBrithday = "";
	private int mGender = 1;

	private EditText edName;
	private EditText edEmail;
	private Profile profile;
	private ToggleButton gender;
	private View btnContact;
	private Assistants currentAssistants;

	public static FragmentAddAssistant newInstance(Bundle bundle) {
		if (fragment == null) {
			fragment = new FragmentAddAssistant();
		}
		if (bundle != null) {
			isUpdate = bundle.getBoolean(Utils.KEY_UPDATE);
		}
		return fragment;
	}

	@Override
	public void onAttach(Activity activity) {
		// TODO Auto-generated method stub
		super.onAttach(activity);
	}

	@Override
	public void onResume() {
		super.onResume();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		mView = inflater.inflate(R.layout.fragment_add_assistiant, null);
		Utils.setOnTouchHideKeyboard(getActivity(), mView);

		return mView;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		Utils.setOnTouchHideKeyboard(getActivity(), mView);
		gender = (ToggleButton) mView.findViewById(R.id.gengerToggle);
		edName = (EditText) mView.findViewById(R.id.lblName);
		edPhone = (EditText) mView.findViewById(R.id.edPhone);
		edEmail = (EditText) mView.findViewById(R.id.lblEmail);
		lblGender = (TextView) mView.findViewById(R.id.lblGender);
		lblTinhthanh = (TextView) mView.findViewById(R.id.lblTinhthanh);
		lblQuanhuyen = (TextView) mView.findViewById(R.id.lblChuyenKhoaName);
		spTinhThanh = (View) mView.findViewById(R.id.spTinhthanh);

		if (isUpdate) {
			currentAssistants = FragmentAssistantList.newInstance()
					.getCurrentAssistants();
			edName.setText(currentAssistants.getFullname());
			edPhone.setText(currentAssistants.getPhone());
		}

		mLoadding = (View) mView.findViewById(R.id.loadding);
		spTinhThanh.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				CityResponse cityResponse = Utils.getCityResponse(
						getActivity(), Utils.KEY_CITY);
				if (cityResponse == null) {
					onLoadCity();
				} else {
					getSelectedCity(cityResponse);
				}

			}
		});

		btnContact = (View) mView.findViewById(R.id.ic_contact);
		btnContact.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(Intent.ACTION_PICK,
						ContactsContract.Contacts.CONTENT_URI);
				getActivity().startActivityForResult(intent,
						Utils.SELECT_PHONE_CONTACT_ADD_ASSISTANT);
			}
		});

		spQuanHuyen = (View) mView.findViewById(R.id.spQuanHuyen);
		spQuanHuyen.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				onLoadDistrict();

			}
		});
		lblNgaysinh = (TextView) mView.findViewById(R.id.lblNgaysinh);
		lblNgaysinh.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				DialogFragment newFragment = new DatePickerFragment(lblNgaysinh);
				newFragment.show(getFragmentManager(), "datePicker");
			}
		});

		gender.setOnToggleChanged(new OnToggleChanged() {

			@Override
			public void onToggle(boolean on) {
				if (on) {
					lblGender.setText("Nam");
					mGender = 1;
				} else {
					mGender = 0;
					lblGender.setText("Nữ");
				}
				// updateInfo();
			}
		});

		userLogin = Utils.getAccountModel(getActivity(), Utils.KEY_USER);
		new CountDownTimer(500, 500) {

			@Override
			public void onTick(long millisUntilFinished) {

			}

			@Override
			public void onFinish() {
				Utils.hideKeyboard(getActivity());
			}
		}.start();

	}

	public void onSetPhone(String phone) {
		edPhone.setText(phone);
	}

	protected void getSelectedCity(CityResponse cityResponse) {
		Utils.showDropdow(getActivity(), cityResponse.getData().getCity(),
				new IRcallBak() {

					@Override
					public void onDisplay(int type, Bundle data) {
						mCity_id = type;
						lblTinhthanh.setText(data
								.getString(Utils.KEY_TINHTHANH));

					}
				}, "Chọn thành phố");

	}

	public void onLoadCity() {
		mLoadding.setVisibility(View.VISIBLE);
		Utils.disableEnableControls(false, mView);

		ServerController.getInstance(getActivity()).requestCity(
				userLogin.getData().getToken(), new OnRequest<CityResponse>() {

					@Override
					public void onSuccess(CityResponse data) {
						Utils.updateData(getActivity(), Utils.KEY_CITY, data);
						mLoadding.setVisibility(View.INVISIBLE);
						Utils.disableEnableControls(true, mView);
						getSelectedCity(data);

					}

					@Override
					public void onError(int errorCode, String message) {
						mLoadding.setVisibility(View.INVISIBLE);
						Utils.disableEnableControls(true, mView);

					}

				});
	}

	public static class DatePickerFragment extends DialogFragment implements
			DatePickerDialog.OnDateSetListener {
		TextView textView;

		public DatePickerFragment(TextView textView) {
			this.textView = textView;
		}

		@Override
		public Dialog onCreateDialog(Bundle savedInstanceState) {
			// Use the current date as the default date in the picker
			final Calendar c = Calendar.getInstance();
			int year = c.get(Calendar.YEAR);
			int month = c.get(Calendar.MONTH);
			int day = c.get(Calendar.DAY_OF_MONTH);

			// Create a new instance of DatePickerDialog and return it
			return new DatePickerDialog(getActivity(), this, year, month, day);
		}

		public void onDateSet(DatePicker view, int year, int month, int day) {
			month++;
			textView.setText(year + "-" + month + "-" + day);
		}
	}

	public void onLoadDistrict() {
		mLoadding.setVisibility(View.VISIBLE);
		Utils.disableEnableControls(false, mView);

		ServerController.getInstance(getActivity()).requestDistrict(
				userLogin.getData().getToken(), mCity_id,
				new OnRequest<DistrictResponse>() {

					@Override
					public void onSuccess(DistrictResponse data) {
						mLoadding.setVisibility(View.INVISIBLE);
						if (data.getResponsecode() < 0)
							return;

						Utils.disableEnableControls(true, mView);
						Utils.showDropdowDistrict(getActivity(), data.getData()
								.getDistrict(), new IRcallBak() {

							@Override
							public void onDisplay(int type, Bundle data) {
								mDistrict_id = type;
								lblQuanhuyen.setText(data
										.getString(Utils.KEY_TINHTHANH));
							}
						}, "Chọn quận huyện");

					}

					@Override
					public void onError(int errorCode, String message) {
						mLoadding.setVisibility(View.INVISIBLE);
						Utils.disableEnableControls(true, mView);

					}

				});
	}

	public void updateInfo() {
		mLoadding.setVisibility(View.VISIBLE);
		Utils.disableEnableControls(false, mView);
		String mFull_name = edName.getText().toString().trim();
		String mPhone = edPhone.getText().toString().trim();
		String email = edEmail.getText().toString().trim();
		mBrithday = lblNgaysinh.getText().toString().trim();

		ServerController.getInstance(getActivity()).requestPushAssistants(
				userLogin.getData().getToken(), mFull_name, mPhone, email,
				mGender, mBrithday, mCity_id, mDistrict_id,
				new OnRequest<DataResponse>() {

					@Override
					public void onSuccess(DataResponse data) {
						mLoadding.setVisibility(View.INVISIBLE);

						if (getActivity() == null)
							return;
						if (data.getResponsecode() > 0) {
							Intent intent = new Intent();
							intent.putExtra(Utils.KEY, Utils.RELOAD_ASSISTIANT);
							getActivity().setResult(Integer.MAX_VALUE, intent);
							getActivity().finish();
						}

					}

					@Override
					public void onError(int errorCode, String message) {
						mLoadding.setVisibility(View.INVISIBLE);
					}

				});
	}
}
